當數據龐大時,我們不會把所有資料都存在同一個資料表,會依照資料類型做分類,例如:使用者資料的users table、文章資料的posts table,這時候資料的關聯就很重要,必須有方法讓我們知道這篇文章是哪個User所發布,所以在這邊簡單介紹Laravel Model要如何撰寫Relationship.
database/migration/2021_09_19_082930_create_posts_table.php規劃了Post table有一個user_id欄位,就是為了能夠知道這篇文章是誰發的,來做資料庫的關聯/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->comment('發文者');
            $table->string('title')->unique()->comment('標題');
            $table->string('content')->comment('內文');
            $table->timestamps();
        });
    }
# App/Models/User.php
/**
 * 取得使用者的文章
 */
public function posts()
{
    return $this->hasMany(Post::class);
}
/**
     * Define a one-to-many relationship.
     *
     * @param  string  $related
     * @param  string|null  $foreignKey
     * @param  string|null  $localKey
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function hasMany($related, $foreignKey = null, $localKey = null)
    {
        $instance = $this->newRelatedInstance($related);
        $foreignKey = $foreignKey ?: $this->getForeignKey();
        $localKey = $localKey ?: $this->getKeyName();
        return $this->newHasMany(
            $instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey
        );
    }
/**
 * 取得文章數量
 *
 * @return mixed
 */
public function getPostList()
{
    try {
        $user = Auth::guard('api')->user();
        $result = User::find($user->id);
        return $result->posts;
    } catch (Exception $e) {
        dd($e);
    }
}
其餘情境可以參考官方文件,寫得非常詳細,其實按照需求去置換function name就好